import {Suspense, useEffect, useState} from "react";
import routes from "@/router/routes.js";
import { Route, Routes, useLocation, useNavigate, useParams, useSearchParams} from "react-router-dom";
import {Mask, Toast} from "antd-mobile";
import {DotLoading} from "antd-mobile/2x";
import store from "@/store/index.js";
import {action} from "@/store/action/index.js";

function isCheckLogin(meta) {
    let {base: {info}} = store.getState()
    return !info && meta.auth;
}

const Element =  function Element(props) {
    // eslint-disable-next-line react/prop-types
    let {component: Component, meta, path} = props;
    let isShow =  !isCheckLogin(meta)
    let [,setRandom] = useState(0)

    useEffect(() => {
        if(isShow) return;
        (async () => {
            let  infoAction = await action.base.queryUserInfoAsync()
            let info = infoAction.info;
            if (!info) {
                Toast.show({
                    content: '请先登录',
                    icon: 'fail'
                })
                navigate(`/login?to=${path}`,{replace: true})
                return
            }
            store.dispatch(infoAction)
            setRandom(new Date().getTime())
        })()

    });

    let {title = 'webApp'} = meta || {};
    document.title = title;
    const navigate = useNavigate(),
        location = useLocation(),
        params = useParams(),
        [usp] = useSearchParams();

    return <>{

        isShow? <Component
            navigate={navigate}
            location={location}
            params={params}
            usp={usp}/> : <Mask visible={true} opacity="thick">
            <DotLoading></DotLoading>
        </Mask>
    }</>
}
export default function RouterView() {
    return (<Suspense fallback={<Mask visible={true} opacity="thick">
        <DotLoading></DotLoading>
    </Mask>}>

        <Routes>
            {
                routes.map((item) => {
                    let {name, path} = item
                    return (<Route key={name} path={path} element={<Element {...item}/>}/>)
                })
            }
        </Routes>
    </Suspense>)
}